package com.easymall.web;

import com.easymall.domain.Category;
import com.easymall.service.CategoryService;
import com.easymall.util.BaseFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "CategoryAddServlet")
public class CategoryAddServlet extends HttpServlet {

    private CategoryService categoryService;

    @Override
    public void init() throws ServletException {
        try {
            categoryService = BaseFactory.getFactory().getInstance(CategoryService.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、获取参数
        String cname = request.getParameter("cname");
        String desc = request.getParameter("desc");
        System.out.println("cname:" + cname);

        // 2、参数验证
        Map<String, String> errorMsg = new HashMap<>();
        if (null == cname || "".equals(cname)) {
            errorMsg.put("cname", "分类名称不能为空");
        }


        if (0 == errorMsg.size()) {
            try {
                // 3、判断分类名称是否存在
                boolean hasCategoryName = categoryService.hasCategoryByName(cname);
                if (hasCategoryName) {
                    // 存在
                    errorMsg.put("cname", "分类名称已经存在！");
                } else {
                    // 4、添加分类
                    Category category = new Category();
                    category.setName(cname);
                    category.setDescription(desc);
                    boolean isSucces = categoryService.saveCategory(category);
                    if (!isSucces) {
                        errorMsg.put("all", "分类添加失败！");
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
                errorMsg.put("all", "分类添加失败，请稍候重试！");
            }
        }

        // 5、响应
        if (errorMsg.size() == 0) {
            request.getRequestDispatcher("/CategoryManageServlet").forward(request, response);
        } else {
            request.setAttribute("errorMsg", errorMsg);
            doGet(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("_category_add.jsp").forward(request, response);
    }
}
